//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by 林柱强 on 16/2/2.
//  Copyright © 2016年 林柱强. All rights reserved.
//  https://api.weibo.com/2/statuses/user_timeline.json

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {

    static let tools:NetworkTools = {
        // 注意: baseURL一定要以/结尾
        let url = NSURL(string: "https://api.weibo.com/")
        let t = NetworkTools(baseURL: url)
        
        // 设置AFN能够接收得数据类型
        t.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as? Set<String>
        return t
    }()
    
    /// 获取单例的方法
    class func shareNetworkTools() -> NetworkTools {
        return tools
    }
    
    /**
     发送微博
     
     - parameter text:            需要发送的正文
     - parameter image:           需要发送的图片
     - parameter successCallback: 成功的回调
     - parameter errorCallback:   失败的回调
     */
    func sendStatus(text: String, image: UIImage?, successCallback: (status: Status) -> (), errorCallback: (error: NSError) -> ()) {
        
        var path = "2/statuses/"
        let parmas = ["access_token": UserAccount.loadAccount()!.access_token!,"status": text]
        
        if image != nil {
            //发送图片微博
//            let path = "2/statuses/upload.json"
//            guard let token = UserAccount.loadAccount()?.access_token else {
//                SVProgressHUD.showErrorWithStatus("客官,您还未登陆哦")
//                return
//            }
//            let parmas = ["access_token": token,"status": text]
            
            path += "upload.json"
            POST(path, parameters: parmas, constructingBodyWithBlock: { (formData) in
                //1.将数据转换为二进制
                let data = UIImagePNGRepresentation(image!)!
                //2.上传数据
                /**
                 第一个参数: 需要上传的二进制数据
                 第二个参数: 服务器对应哪个的字段名称
                 第三个参数: 文件的名称（在大部分服务器上可以随便写）
                 第四个参数: 数据的类型，通用类型 application/octet-stream
                 */
                formData.appendPartWithFileData(data, name: "pic", fileName: "abc.png", mimeType: "application/octet-stream")
                
                }, success: { (_, JSON) in
                    successCallback(status: Status(dict: JSON as! [String : AnyObject]))
                }, failure: { (_, error) in
                    errorCallback(error: error)
            })
        }else {
            //发送文字微博
            path += "update.json"
            POST(path, parameters: parmas, success: { (_, JSON) -> Void in
                successCallback(status: Status(dict: JSON as! [String : AnyObject]))
            }) { (_, error) -> Void in
                errorCallback(error: error)
            }
        }
    }
}
